'use client'

import { useState } from 'react'
import { useChat } from 'ai/react'
import ReactMarkdown from 'react-markdown'
import { Card, Button, Input, Typography, Space, Avatar, message } from 'antd'
import { SendOutlined, CopyOutlined, StopOutlined, UserOutlined, RobotOutlined } from '@ant-design/icons'

const { TextArea } = Input
const { Title, Text } = Typography

export default function AIChat() {
  const [input, setInput] = useState('')

  const { messages, handleSubmit, isLoading, stop } = useChat({
    api: '/api/generate',
    onFinish: () => {
      // 自动滚动到底部
      const el = document.getElementById('chat-end')
      el?.scrollIntoView({ behavior: 'smooth', block: 'end' })
    }
  })

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (input.trim()) {
      handleSubmit(e, { data: { input } })
      setInput('')
    }
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    message.success('已复制到剪贴板')
  }

  return (
    <div>
      <Title level={2}>AI 对话</Title>
      <Text type="secondary">与AI助手进行智能对话</Text>
      
      <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 200px)' }}>
        {/* 对话区域 */}
        <div style={{ flex: 1, overflowY: 'auto', marginBottom: 16 }}>
          {messages.length === 0 ? (
            <Card>
              <div style={{ textAlign: 'center', padding: '40px 20px' }}>
                <RobotOutlined style={{ fontSize: '48px', color: '#1890ff', marginBottom: '16px' }} />
                <Title level={4}>开始与AI助手对话</Title>
                <Text type="secondary">您可以询问任何问题，AI助手会尽力帮助您</Text>
              </div>
            </Card>
          ) : (
            <Space direction="vertical" style={{ width: '100%' }}>
              {messages.map(m => (
                <Card 
                  key={m.id} 
                  size="small"
                  style={{ 
                    borderColor: m.role === 'user' ? '#d9d9d9' : '#f0f0f0',
                    backgroundColor: m.role === 'user' ? '#fff' : '#fafafa'
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px' }}>
                    <Avatar 
                      icon={m.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
                      style={{ 
                        backgroundColor: m.role === 'user' ? '#1890ff' : '#52c41a',
                        flexShrink: 0
                      }}
                    />
                    <div style={{ flex: 1 }}>
                      <div style={{ marginBottom: 8, fontSize: '12px', color: '#666' }}>
                        {m.role === 'user' ? '你' : 'AI助手'}
                      </div>
                      <div style={{ lineHeight: 1.6 }}>
                        <ReactMarkdown>{m.content || ''}</ReactMarkdown>
                      </div>
                      {m.role !== 'user' && (
                        <div style={{ marginTop: 12 }}>
                          <Button 
                            size="small"
                            onClick={() => copyToClipboard(m.content || '')}
                            icon={<CopyOutlined />}
                          >
                            复制回复
                          </Button>
                        </div>
                      )}
                    </div>
                  </div>
                </Card>
              ))}
              <div id="chat-end" />
            </Space>
          )}
        </div>

        {/* 输入区域 */}
        <Card>
          <form onSubmit={onSubmit}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <TextArea
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="输入您的问题..."
                autoSize={{ minRows: 3, maxRows: 6 }}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault()
                    onSubmit(e as any)
                  }
                }}
              />
              <div style={{ display: 'flex', gap: 8, justifyContent: 'space-between' }}>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  按 Enter 发送，Shift + Enter 换行
                </Text>
                <Space>
                  {isLoading && (
                    <Button 
                      onClick={() => stop()} 
                      icon={<StopOutlined />}
                    >
                      停止
                    </Button>
                  )}
                  <Button 
                    type="primary" 
                    htmlType="submit" 
                    icon={<SendOutlined />}
                    loading={isLoading}
                    disabled={!input.trim()}
                  >
                    发送
                  </Button>
                </Space>
              </div>
            </Space>
          </form>
        </Card>
      </div>
    </div>
  )
} 